<?php


require_once 'vo/player/PlayerVO.php';



class Database
{

	const PLAYERS_TABLE_FILE = "data/player/players.txt";
	
	public function __construct()
	{
		$files = array(self::PLAYERS_TABLE_FILE);
		
		foreach( $files as $url )
		{
			if ( !file_exists($url) )
			{
				file_put_contents($url, serialize(array()));
			}
		}
	}
	
	public function truncatePlayers()
	{
		$this->savePlayersData(array());
	}

	public function addUser( $email, $password, $name )
	{
		$players = $this->getPlayersData();
		
		$vo = new PlayerVO();
		$vo->email = $email;
		$vo->password = $password;
		$vo->name = $name;
		$vo->id = count($players);
		
		array_push( $players, $vo );
		$this->savePlayersData($players);
	}
	
	public function getUser( $email, $password )
	{
		$players = $this->getPlayersData();
		$i = count($players);
		
		while ( --$i > -1 )
		{
			if ( $players[$i]->email == $email && $players[$i]->password == $password )
			{
				return $players[$i];
			}
		}
		
		return null;
	}
	
	
	public function getPlayersData()
	{
		return unserialize( file_get_contents(self::PLAYERS_TABLE_FILE) );
	}
	
	public function savePlayersData($data)
	{
		file_put_contents(self::PLAYERS_TABLE_FILE, serialize($data) );
	}

}

?>